﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Common.BaseLibrary.Authorization;
using Common.BaseLibrary.Logger;
using DepartmentWork.Migrator.Data;
using DepartmentWork.Model;
using DepartmentWork.Platform.Controllers;

namespace DepartmentWork.Platform.Areas.DevelopArea.Controllers
{
    public class TaskController : BaseController
    {
        // GET: DevelopArea/Task
        public ActionResult ProjectTaskList(string projectId, string flag = "", string flagInfo = "")
        {
            Guid proId = new Guid(projectId);

            #region 设置分页

            var pageSize = this.Request["pageSize"] == null ? 10 : int.Parse(Request["pageSize"]);
            var pageIndex = this.Request["pageIndex"] == null ? 1 : int.Parse(Request["pageIndex"]);

            ViewData["pageIndex"] = pageIndex;
            ViewData["pageSize"] = pageSize;

            #endregion


            #region 校验该登录用户是否是项目负责人

            ViewBag.IsDevelopLeader = false;

            #region 原版

            //if (CurrentUser.UserID.Length != 0)
            //{
            //    Guid userGuid = new Guid(CurrentUser.UserID);
            //    USER_INFO user = userRepository.GetModel(r => r.USER_ID == userGuid).FirstOrDefault();
            //    PROJECT_DEVELOP_USER developUser = projectDevelopUserRepository.GetModel(r => r.USER_ID == user.USER_ID && r.PROJECT_ID == proId).FirstOrDefault();
            //    if (developUser != null)
            //    {
            //        if (developUser.USER_POSITION == 1)
            //        {
            //            ViewBag.IsDevelopLeader = true;
            //        }
            //    }
            //}

            #endregion


            #region 改版后

            //1 、 获取当前用户所在角色
            //2. 获取该角色 所具有的 所有 权限
            //3. 确认该角色是否具有该权限
            Guid userGuid = new Guid(CurrentUser.UserID);
            USER_INFO user = userRepository.GetModel(r => r.USER_ID == userGuid).FirstOrDefault();
            USER_TEAMSAPCE userTeam = userTeamsapceRepository.GetModel(r => r.USER_ID == user.USER_ID).FirstOrDefault();
            ROLE_INFO role = roleRepository.GetModel(r => r.ROLE_ID == userTeam.ROLE_ID).FirstOrDefault();
            List<AUTHORITY_ROLE> authRoleList =
                authorityRoleRepository.GetModel(r => r.ROLE_ID == role.ROLE_ID).ToList();



            for (int i = 0; i < authRoleList.Count; i++)
            {
                bool result = false;
                result =
                    empAuthorityRepository.GetModel(r => r.AUTHORITY_ID == authRoleList[i].AUTHORITY_ID)
                        .FirstOrDefault()
                        .AUTHORITY_TITLE.Contains("开发管理项目细节操作");
                if (result == true)
                {
                    ViewBag.IsDevelopLeader = true;
                    break;

                }
            }

            #endregion

            #endregion

            List<PROJECT_DEVELOP_TASK> taskList = projectDevelopTaskRepository.GetModel(r => r.PROJECT_ID == proId).OrderByDescending(r => r.CREATE_TIME).Take(pageSize * pageIndex).Skip(pageSize * (pageIndex - 1)).ToList();
            ViewData["total"] = projectDevelopTaskRepository.GetModel(r => r.PROJECT_ID == proId).Count();
            Guid teamSpaceId =
                projectDevelopRepository.GetModel(r => r.PROJECT_DEVELOP_ID == proId).FirstOrDefault().TEAMSPACE_ID;

            #region 获取该团队空间下全部的人员

            List<UserInfoViewModel> userList = new List<UserInfoViewModel>();
            List<USER_TEAMSAPCE> userTeams = userTeamsapceRepository.GetModel(r => r.TEAMSPACE_ID == teamSpaceId).ToList();
            userList.AddRange((from item in userTeams
                               select new UserInfoViewModel()
                               {
                                   UserId = item.USER_ID,
                               }).ToList());
            for (int i = 0; i < userList.Count(); i++)
            {
                var id = userList[i].UserId;
                userList[i].UserName =
                    userRepository.GetModel(r => r.USER_ID == id).FirstOrDefault().DISPLAY_NAME;
            }
            TempData["UserList"] = userList;

            #endregion

            ViewBag.ProjectId = projectId;
            PROJECT_DEVELOP project = projectDevelopRepository.GetModel(r => r.PROJECT_DEVELOP_ID == proId).FirstOrDefault();
            ViewBag.ProjectName = project.PROJECT_NAME;
            ViewBag.Flag = flag;
            ViewBag.FlagInfo = flagInfo;
            List<ProjectTaskViewModel> model = new List<ProjectTaskViewModel>();

            for (int i = 0; i < taskList.Count; i++)
            {
                Guid userId = taskList[i].CREATER;
                string showName = userRepository.GetModel(r => r.USER_ID == userId).FirstOrDefault().DISPLAY_NAME;
                ProjectTaskViewModel item = new ProjectTaskViewModel();
                item.TaskContext = taskList[i].TASK_CONTEXT;
                item.TaskCreateTime = taskList[i].CREATE_TIME.ToString("yyyy-MM-dd");
                item.TaskId = taskList[i].TASK_ID;
                item.TaskName = taskList[i].TASK_NAME;
                item.Creater = showName;
                item.CreaterId = userId.ToString();
                item.HandToUser = taskList[i].HANDTO_USER.ToString();
                item.TaskCheckState = taskList[i].CHECK_FLAG;
                //如果审核标志不为 2 ==>表明任务尚未完成
                if (taskList[i].CHECK_FLAG != 2)
                {
                    //如果审核时间大于结束时间 ==>表明任务超时
                    if (taskList[i].CHECK_TIME != null && DateTime.Compare((DateTime)taskList[i].CHECK_TIME, taskList[i].DEADTIME) > 0)
                    {
                        item.Status = 3;//任务超时完成
                    }
                    else
                    {
                        item.Status = 2;//任务正常完成
                    }
                }
                else
                {
                    //如果审核时间大于结束时间 ==>表明任务超时
                    if (taskList[i].CHECK_TIME != null && DateTime.Compare((DateTime)taskList[i].CHECK_TIME, taskList[i].DEADTIME) > 0)
                    {
                        item.Status = 3;//任务超时完成
                    }
                    else
                    {
                        if (DateTime.Compare(DateTime.Now, taskList[i].DEADTIME) > 0)
                        {
                            item.Status = 1;//任务超时并且没有完成
                        }
                        else
                        {
                            item.Status = 0;//任务进行中
                        }
                    }
                }

                model.Add(item);
            }

            return this.View(model);
        }

        [HttpPost]
        public ActionResult CreateTask(FormCollection collection)
        {
            PROJECT_DEVELOP_TASK taskModel = new PROJECT_DEVELOP_TASK();
            FILEINFO fileModel = new FILEINFO();
            taskModel.TASK_ID = Guid.NewGuid();
            taskModel.PROJECT_ID = new Guid(collection["hid_ProjectId"]);
            taskModel.TASK_NAME = collection["tb_TaskName"];
            taskModel.CREATER = new Guid(CurrentUser.UserID);
            taskModel.TASK_CONTEXT = collection["tb_TaskContext"];
            taskModel.HOUR = Convert.ToInt32(collection["tb_TaskHour"]);
            taskModel.DEADTIME = Convert.ToDateTime(collection["tb_DeadTime"]);
            taskModel.TASK_LEVEL = Convert.ToInt32(collection["select_TaskLevel"]);
            taskModel.HANDTO_USER = new Guid(collection["select_TaskHandToUser"]);
            taskModel.CREATE_TIME = DateTime.Now;
            taskModel.CHECK_FLAG = 0;
            taskModel.CHECK_TIME = null;
            string temp = ConfigurationManager.AppSettings["UpLoadPath"] + @"\Task\";
            int fileCount = this.Request.Files.Count;

            HttpPostedFile[] upFiles = new HttpPostedFile[fileCount];
            this.Request.Files.CopyTo(upFiles, 0);
            if (upFiles[0].FileName != "")
            {
                try
                {
                    string fileSaveName = string.Empty;
                    HttpPostedFile hpf;
                    hpf = upFiles[0];
                    string savePath = "";
                    string fullUpLoadPath = "";
                    Guid fileName = Guid.NewGuid();
                    fileSaveName = string.Format("{0}{1}", fileName, Path.GetExtension(hpf.FileName));
                    fullUpLoadPath = Path.Combine(temp, fileSaveName);
                    hpf.SaveAs(Path.Combine(fullUpLoadPath));

                    fileModel.FILE_ID = fileName;
                    fileModel.FILE_SHOWNAME = upFiles[0].FileName.Split('\\')[upFiles[0].FileName.Split('\\').Length - 1];
                    fileModel.FILE_SAVEPATH = fullUpLoadPath;
                    fileModel.FILE_SAVENAME = fileSaveName;
                    fileModel.FILE_CREATER = new Guid(CurrentUser.UserID);
                    fileModel.FILE_TYPE = "DEVELOP_TASK";
                    fileModel.FILE_CREATETIME = DateTime.Now;
                    fileModel.CONTACT_ID = taskModel.TASK_ID;

                    fileRepository.Insert(fileModel);

                }
                catch (Exception ex)
                {
                    LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "任务创建失败！ 信息："+ex.Message);

                    return RedirectToAction("ProjectTaskList", "Task", new { area = "DevelopArea", flag = "CreateFalse", flagInfo = ex.Message, projectId = taskModel.PROJECT_ID });
                }
            }
            try
            {
                projectDevelopTaskRepository.Insert(taskModel);
                LoggerFactory.Instance.Logger_Info(CurrentUser.UserName + " " + DateTime.Now + " " + "任务创建成功！");

                return RedirectToAction("ProjectTaskList", "Task", new { area = "DevelopArea", flag = "CreateTrue", projectId = taskModel.PROJECT_ID });
            }
            catch (Exception ex)
            {
                LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "任务创建失败！ 信息：" + ex.Message);

                return RedirectToAction("ProjectTaskList", "Task", new { area = "DevelopArea", flag = "CreateFalse", flagInfo = ex.Message, projectId = taskModel.PROJECT_ID });
            }
        }


        [HttpPost]
        public JsonResult GetTaskInfo(Guid taskId)
        {

            PROJECT_DEVELOP_TASK task = projectDevelopTaskRepository.GetModel(r => r.TASK_ID == taskId).FirstOrDefault();
            FILEINFO file =
                fileRepository.GetModel(r => r.FILE_TYPE == "DEVELOP_TASK" && r.CONTACT_ID == taskId)
                    .FirstOrDefault();

            Guid userId = task.CREATER;
            string showName = userRepository.GetModel(r => r.USER_ID == userId).FirstOrDefault().DISPLAY_NAME;
            Guid HandToUserGuid = task.HANDTO_USER;
            ProjectTaskViewModel model = new ProjectTaskViewModel();
            model.Creater = showName;
            model.CreaterId = userId.ToString();
            model.TaskId = taskId;
            model.Level = task.TASK_LEVEL;
            model.TaskDeadTime = task.DEADTIME.ToString("yyyy-MM-dd");
            model.TaskContext = task.TASK_CONTEXT;
            model.TaskCreateTime = task.CREATE_TIME.ToString("yyyy-MM-dd");
            model.TaskName = task.TASK_NAME;
            model.Hour = task.HOUR;
            model.HandToUser = userRepository.GetModel(r => r.USER_ID == HandToUserGuid).FirstOrDefault().DISPLAY_NAME;
            //如果审核标志不为 2 ==>表明任务尚未完成
            if (task.CHECK_FLAG != 2)
            {
                //如果审核时间大于结束时间 ==>表明任务超时
                if (task.CHECK_TIME != null && DateTime.Compare((DateTime)task.CHECK_TIME, task.DEADTIME) > 0)
                {
                    model.Status = 3;//任务超时完成
                }
                else
                {
                    model.Status = 2;//任务正常完成
                }
            }
            else
            {
                //如果审核时间大于结束时间 ==>表明任务超时
                if (task.CHECK_TIME != null && DateTime.Compare((DateTime)task.CHECK_TIME, task.DEADTIME) > 0)
                {
                    model.Status = 1;//任务超时并且没有完成
                }
                else
                {
                    if (DateTime.Compare(DateTime.Now, task.DEADTIME) > 0)
                    {
                        model.Status = 1;//任务超时并且没有完成
                    }
                    else
                    {
                        model.Status = 0;//任务进行中
                    }
                }
            }


            if (file != null && file.FILE_ID.ToString().Trim() != "")
            {
                model.TaskFileId = file.FILE_ID;
                model.TaskFilePath = file.FILE_SAVEPATH;
                model.TaskFileSaveName = file.FILE_SAVENAME;
                model.TaskFileShowName = file.FILE_SHOWNAME;
            }
            else
            {
                //model.TaskBookFileId = file.FILE_ID;
                model.TaskFilePath = "";
                model.TaskFileSaveName = "";
                model.TaskFileShowName = "";
            }

            //ViewBag.CreateTaskBookModel = model;

            return this.Json(model);

        }


        [HttpPost]
        public ActionResult EditTask(FormCollection collection)
        {
            Guid taskId = new Guid(collection["hid_EditTaskId"]);
            PROJECT_DEVELOP_TASK taskModel =
                projectDevelopTaskRepository.GetModel(r => r.TASK_ID == taskId).FirstOrDefault();
            FILEINFO fileModel = new FILEINFO();
            string temp = ConfigurationManager.AppSettings["UpLoadPath"] + @"\Task\";

            #region 获取界面数据

            try
            {
                taskModel.HANDTO_USER = new Guid(collection["select_EditTaskHandToUser"]);
                taskModel.TASK_NAME = collection["tb_TaskName"] == "" ? taskModel.TASK_NAME : collection["tb_TaskName"];
                taskModel.CREATER = new Guid(CurrentUser.UserID);
                taskModel.TASK_CONTEXT = collection["tb_TaskContext"] == "" ? taskModel.TASK_CONTEXT : collection["tb_TaskContext"];
                taskModel.CREATE_TIME = DateTime.Now;
                taskModel.DEADTIME = collection["tb_DeadTime"] == "" ? taskModel.DEADTIME : (Convert.ToDateTime(collection["tb_DeadTime"]));
                taskModel.TASK_LEVEL = Convert.ToInt32(collection["select_EditTaskLevel"]);
                taskModel.HOUR = collection["tb_Hour"] == "" ? taskModel.HOUR : (Convert.ToInt32(collection["tb_Hour"]));
            }
            catch (Exception ex)
            {
                return RedirectToAction("ProjectTaskList", "Task", new { area = "DevelopArea", flag = "EditFalse", flagInfo = ex.Message, projectId = taskModel.PROJECT_ID });
            }

            #endregion

            int fileCount = this.Request.Files.Count;

            HttpPostedFile[] upFiles = new HttpPostedFile[fileCount];
            this.Request.Files.CopyTo(upFiles, 0);
            if (upFiles[0].FileName != "")
            {
                #region 删除旧文件记录

                try
                {
                    FILEINFO oldFile =
                        fileRepository.GetModel(r => r.CONTACT_ID == taskId && r.FILE_TYPE == "DEVELOP_TASK").FirstOrDefault();
                    fileRepository.Delete(oldFile);
                }
                catch (Exception ex)
                {
                    return RedirectToAction("ProjectTaskList", "Task", new { area = "DevelopArea", flag = "EditFalse", flagInfo = ex.Message, projectId = taskModel.PROJECT_ID });
                }


                #endregion

                #region 上传新文件 并向数据库中插入数据

                try
                {
                    string fileSaveName = string.Empty;
                    HttpPostedFile hpf;
                    hpf = upFiles[0];
                    string fullUpLoadPath = "";
                    Guid fileName = Guid.NewGuid();
                    fileSaveName = string.Format("{0}{1}", fileName, Path.GetExtension(hpf.FileName));
                    fullUpLoadPath = Path.Combine(temp, fileSaveName);
                    hpf.SaveAs(Path.Combine(fullUpLoadPath));

                    fileModel.FILE_ID = fileName;
                    fileModel.FILE_SHOWNAME = upFiles[0].FileName.Split('\\')[upFiles[0].FileName.Split('\\').Length - 1];
                    fileModel.FILE_SAVEPATH = fullUpLoadPath;
                    fileModel.FILE_SAVENAME = fileSaveName;
                    fileModel.FILE_CREATETIME = DateTime.Now;
                    fileModel.FILE_CREATER = new Guid(CurrentUser.UserID);
                    fileModel.FILE_TYPE = "DEVELOP_TASK";
                    fileModel.CONTACT_ID = taskModel.TASK_ID;
                    fileRepository.Insert(fileModel);

                }
                catch (Exception ex)
                {
                    LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "任务编辑失败！ 信息："+ex.Message);

                    return RedirectToAction("ProjectTaskList", "Task", new { area = "DevelopArea", flag = "EditFalse", flagInfo = ex.Message, projectId = taskModel.PROJECT_ID });
                }

                #endregion
            }
            try
            {
                projectDevelopTaskRepository.Update(taskModel);
                LoggerFactory.Instance.Logger_Info(CurrentUser.UserName + " " + DateTime.Now + " " + "任务编辑成功！");

                return RedirectToAction("ProjectTaskList", "Task", new { area = "DevelopArea", flag = "EditTrue", projectId = taskModel.PROJECT_ID });
            }
            catch (Exception ex)
            {
                LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "任务编辑失败！ 信息：" + ex.Message);

                return RedirectToAction("ProjectTaskList", "Task", new { area = "DevelopArea", flag = "EditFalse", flagInfo = ex.Message, projectId = taskModel.PROJECT_ID });
            }
        }


        [HttpGet]
        public ActionResult DeleteTask(Guid taskId)
        {
            PROJECT_DEVELOP_TASK model = projectDevelopTaskRepository.GetModel(r => r.TASK_ID == taskId).FirstOrDefault();
            Guid proId = model.PROJECT_ID;
            FILEINFO file =
                fileRepository.GetModel(r => r.CONTACT_ID == taskId && r.FILE_TYPE == "DEVELOP_TASK")
                    .FirstOrDefault();

            try
            {
                projectDevelopTaskRepository.Delete(model);
                if (file != null && file.FILE_ID.ToString() != "")
                {
                    fileRepository.Delete(file);
                }
                LoggerFactory.Instance.Logger_Info(CurrentUser.UserName + " " + DateTime.Now + " " + "任务删除成功！ " );

                return RedirectToAction("ProjectTaskList", "Task", new { area = "DevelopArea", flag = "DelTrue", projectId = proId });

            }
            catch (Exception ex)
            {
                LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "任务删除失败！ 信息：" + ex.Message);

                return RedirectToAction("ProjectTaskList", "Task", new { area = "DevelopArea", flag = "DelFalse", flagInfo = ex.Message, projectId = proId });
            }


        }

        /// <summary>
        /// 提交任务
        /// </summary>
        /// <param name="TaskId"></param>
        /// <returns></returns>
        public ActionResult SubmitTask(Guid TaskId)
        {
            PROJECT_DEVELOP_TASK model = projectDevelopTaskRepository.GetModel(r => r.TASK_ID == TaskId).FirstOrDefault();
            try
            {
                model.CHECK_FLAG = 1;
                model.CHECK_TIME = DateTime.Now;
                projectDevelopTaskRepository.Update(model);

                LoggerFactory.Instance.Logger_Info(CurrentUser.UserName + " " + DateTime.Now + " " + "任务提交成功！" );

                return RedirectToAction("ProjectTaskList", "Task", new { area = "DevelopArea", flag = "SubmitTrue", projectId = model.PROJECT_ID });
            }
            catch (Exception ex)
            {
                LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "任务提交失败！ 信息：" + ex.Message);

                return RedirectToAction("ProjectTaskList", "Task", new { area = "DevelopArea", flag = "SubmitFalse", flagInfo = ex.Message, projectId = model.PROJECT_ID });
            }
        }

        /// <summary>
        /// 审核任务
        /// </summary>
        /// <param name="TaskId"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult PassTask(string TaskId)
        {
            Guid tid=new Guid(TaskId);
            PROJECT_DEVELOP_TASK model = projectDevelopTaskRepository.GetModel(r => r.TASK_ID == tid).FirstOrDefault();
            try
            {

                model.CHECK_FLAG = 2;
                //model.CHECK_TIME = DateTime.Now;
                projectDevelopTaskRepository.Update(model);
                LoggerFactory.Instance.Logger_Info(CurrentUser.UserName + " " + DateTime.Now + " " + "任务审核成功！" );

                return RedirectToAction("ProjectTaskList", "Task", new { area = "DevelopArea", flag = "PassTrue", projectId = model.PROJECT_ID });
            }
            catch (Exception ex)
            {
                LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "任务审核失败！ 信息：" + ex.Message);

                return RedirectToAction("ProjectTaskList", "Task", new { area = "DevelopArea", flag = "PassFalse", flagInfo = ex.Message, projectId = model.PROJECT_ID });
            }
        }
        
        /// <summary>
        /// 退回任务
        /// </summary>
        /// <param name="TaskId"></param>
        /// <returns></returns>
        public ActionResult ReturnTask(Guid TaskId)
        {
            PROJECT_DEVELOP_TASK model = projectDevelopTaskRepository.GetModel(r => r.TASK_ID == TaskId).FirstOrDefault();

            try
            {
                model.CHECK_FLAG = 0;
                projectDevelopTaskRepository.Update(model);
                LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "任务退回成功！" );

                return RedirectToAction("ProjectTaskList", "Task", new { area = "DevelopArea", flag = "ReturnTrue", projectId = model.PROJECT_ID });
            }
            catch (Exception ex)
            {
                LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "任务退回失败！ 信息：" + ex.Message);

                return RedirectToAction("ProjectTaskList", "Task", new { area = "DevelopArea", flag = "ReturnFalse", flagInfo = ex.Message, projectId = model.PROJECT_ID });
            }
        }

    }
}